import json
import os
import requests

# 判断是否存在文件
if os.path.exists('herolist.json'):
    with open('herolist.json', 'r') as f:
        herolist_json = json.load(f)
else:
    list_url = 'https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js'
    herolist = requests.get(list_url)
    herolist_json = herolist.json()

    # 保存到文件
    with open('herolist.json', 'w') as f:
        json.dump(herolist_json, f)

version = herolist_json['version']
fileTime = herolist_json['fileTime']
heroId = list(map(lambda x: x['heroId'], herolist_json['hero']))

# 获取英雄类型字典
hero_job_dict = {
    'fighter': '战士',
    'mage': '法师',
    'assassin': '刺客',
    'tank': '坦克',
    'marksman': '射手',
    'support': '辅助'
}

# 获取英雄信息字典
hero_dict = {}
for hero in herolist_json['hero']:
    # 将英雄类型对应的英文名称转换为中文名称
    hero['roles_CN'] = [hero_job_dict.get(role, role) for role in hero['roles']]
    hero_dict[hero['heroId']] = hero


# 根据英雄id查询信息
def get_hero_info_by_id(hero_id):
    if hero_id in hero_dict:
        hero = hero_dict[hero_id]
        return hero
    else:
        return None


# 打印所有英雄信息
def print_all_heroes_info():
    for hero_id in heroId:
        if hero_id in hero_dict:
            hero = hero_dict[hero_id]
            print("-----------------------------------------")
            print("英雄id：", hero['heroId'])
            print("英雄名字：", hero['name'] + ' ' + hero['title'])
            print("英雄英文名：", hero['alias'])
            try:
                hero['isWeekFree'] == "1"
                isWeedFree = "周免"
            except KeyError:
                isWeedFree = "非周免"
            print("是否周免费:", isWeedFree)
            # 输出转换后的中文名称
            print("英雄定位：", hero['roles_CN'])
            print("攻击评分：", hero['attack'])
            print("防御评分：", hero['defense'])
            print("法术评分：", hero['magic'])
            print("难度评分：", hero['difficulty'])
            print("蓝色精粹价格:", hero['goldPrice'])
            print("黄色精粹价格:", hero['couponPrice'])
            print("改动", hero['changeLabel'])
            try:
                print("关键词", hero['keywords'])
            except KeyError:
                print("该英雄没有称号")
            print("-----------------------------------------")
        else:
            print("未找到对应英雄")


# 根据关键词查询英雄信息
def search_hero_by_keyword(keyword):
    match_heroes = []

    for hero_id in heroId:
        if hero_id in hero_dict:
            hero = hero_dict[hero_id]
            try:
                keywords = hero['keywords']
            except KeyError:
                continue
            if keyword in keywords:
                match_heroes.append(hero)

    if not match_heroes:
        print("未找到和关键词匹配的英雄")
    else:
        for hero in match_heroes:
            print("-----------------------------------------")
            print("英雄id：", hero['heroId'])
            print("英雄名字：", hero['name'] + ' ' + hero['title'])
            print("英雄英文名：", hero['alias'])
            print("英雄类型：", '/'.join(hero['roles_CN']))
            print("出自：", hero['camp'])
            try:
                print("获得方式：", hero['pay_type'])
            except  KeyError:
                print("获得方式：", "null")
            print("蓝色精粹价格：", hero['goldPrice'])
            print("黄色精粹价格：", hero['couponPrice'])
            print("改动：", hero['changeLabel'])
            print("关键词：", hero['keywords'])


isRun = True

while isRun:
    active = input('请输入操作( 1.查询id / 2.输出所有 / 3.关键词查询 /4.下载所有图片 /5.退出):')
    if active == '1.查询id' or active == "1" or active == '查询id':
        # 根据英雄id查询信息
        hero_id = input('请输入英雄id')
        hero_info = get_hero_info_by_id(hero_id)
        if hero_info:
            print("英雄id：", hero_info['heroId'])
            print("英雄名字：", hero_info['name'] + ' ' + hero_info['title'])
            print("英雄英文名：", hero_info['alias'])
            try:
                hero_info['isWeekFree'] == "1"
                isWeedFree = "周免"
            except KeyError:
                isWeedFree = "非周免"
            print("是否周免费:", isWeedFree)
            # 输出转换后的中文名称
            print("英雄定位：", hero_info['roles_CN'])
            print("攻击评分：", hero_info['attack'])
            print("防御评分：", hero_info['defense'])
            print("法术评分：", hero_info['magic'])
            print("难度评分：", hero_info['difficulty'])
            print("蓝色精粹价格:", hero_info['goldPrice'])
            print("黄色精粹价格:", hero_info['couponPrice'])
            print("改动", hero_info['changeLabel'])
            try:
                print("关键词", hero_info['keywords'])
            except KeyError:
                print('该英雄没有称号')
        else:
            print('未找到对应英雄')


    elif active == '2.输出所有' or active == "2" or active == '输出所有':
        print_all_heroes_info()

    elif active == '3.关键词查询' or active == "3" or active == '关键词查询':
        search_hero_by_keyword(input('请输入关键词:'))

    elif active == '4.下载所有图片' or active == "4" or active == '下载所有图片':
        for heroid in heroId:

            herojs_url = "https://game.gtimg.cn/images/lol/act/img/js/hero/{}.js".format(heroid)
            herojs = requests.get(herojs_url).json()
            heroname = herojs['hero']['name'] + herojs['hero']['title']
            try:
                os.mkdir(heroname)
                print("\n\n[+] 文件夹【{}】创建成功，开始下载皮肤".format(heroname))
            except FileExistsError:
                print("\n\n[!] 文件夹【{}】已存在，开始下载皮肤".format(heroname))

            for skin in herojs['skins']:
                skinname = skin['name']
                print("[-] 正在下载【{}】".format(skinname))
                skinurl = skin['mainImg']

                try:
                    skin_jpg = requests.get(skinurl)
                    if skin_jpg.status_code == 200:
                        f = open(heroname + "\\" + skinname + ".jpg", "wb")
                        f.write(skin_jpg.content)
                        f.close()
                except:
                    print("[!] 【{}】为炫彩皮肤无图片".format(skinname))
    elif active == '5.退出' or active == '5' or active == 'exit' or active == "5":
        break
print('----- 程序结束   The End-----')

#
# for heroid in heroId:
#
#     herojs_url = "https://game.gtimg.cn/images/lol/act/img/js/hero/{}.js".format(heroid)
#     herojs = requests.get(herojs_url).json()
#     heroname = herojs['hero']['name'] + herojs['hero']['title']
#     try:
#         os.mkdir(heroname)
#         print("\n\n文件夹{}创建成功，开始下载皮肤".format(heroname))
#     except FileExistsError:
#         print("\n\n文件夹{}已存在，开始下载皮肤".format(heroname))
#
#     for skin in herojs['skins']:
#         skinname = skin['name']
#         print("开始下载{}".format(skinname))
#         skinurl = skin['mainImg']
#
#         try:
#             skin_jpg = requests.get(skinurl)
#             if skin_jpg.status_code == 200:
#                 f = open(heroname + "\\" + skinname + ".jpg", "wb")
#                 f.write(skin_jpg.content)
#                 f.close()
#         except:
#             print("{}为炫彩皮肤无图片".format(skinname))
#
